#include <iostream>
#include <memory>
#include "TcpServer.hpp"
#include "Epoller.hpp"
#include "Socket.hpp"
#include "LogMessage.hpp"
#include "Accept.hpp"

//在epoll模型的ET工作模式下，每一个套接字都要有独立的
//发送和接受缓冲区

const int defaultport = 8080;

int main()
{
    // 1.创建listen套接字并设置为非阻塞
    Socket* listensock = new(TcpSocket);
    listensock->CreateBindListenSocket(defaultport);
    SetNonBlocking(listensock->GetSockfd());

    // 2.创建Epoll模型
    Epoller* epoll = new(Epoller);

    // 3.将listensock添加到Epoll模型当中
    epoll->AddEpoll(listensock->GetSockfd(), EPOLLIN | EPOLLET);

    // 4.创建TCP服务器对象
    TcpServer* ptr = new TcpServer(listensock, epoll);
    Accepter* accepter = new Accepter;

    // 5.创建listen的Connect对象
    Connect* listenconnect = new Connect(listensock, ptr);
    auto acceptconnect = std::bind(&Accepter::ListenAccepter, accepter, listensock, epoll, ptr);
    listenconnect->Establishment(acceptconnect, nullptr, nullptr);

    // 6.将Connect对象添加进Tcp服务器中
    ptr->AddConnection(listensock->GetSockfd(), listenconnect);

    // 7.启动服务器
    ptr->Start();

    // n.内存释放
    close(listensock->GetSockfd());
    delete listensock;
    delete epoll;
    delete accepter;
    // 所有Connect对象以及sockfd都交给TCP对象去释放
    delete ptr;

    return 0;
}